import { constantRoutes } from '@/router'
import { getRouters } from '@/api/menu'
// import { getSonRouters } from '@/api/menu'
import Layout from '@/layout/index'
import { deepClone, arrayToTree } from '@/utils'
import Cookies from 'js-cookie'

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    routeList: [], // 保存原始菜单数据
    leftList: [], // 左侧菜单
    leftActive: '', // 当前激活的左侧菜单
    navActive: '' // 当前菜单栏
  },
  getters: {
    leftActive: state => {
      const activeMenu = Cookies.get('_sider_bar_active_') || ''
      return state.leftActive || activeMenu
    },
    navActive: state => {
      const navActive = Cookies.get('_nav_active_') || ''
      return state.navActive || navActive
    }
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_ROUTELIST(state, routes) {
      state.routeList = constantRoutes.concat(routes)
    },
    SET_LEFTLIST(state, leftList) {
      state.leftList = leftList
    },
    SET_LEFTACTIVE(state, leftActive) {
      state.leftActive = leftActive
    },
    SET_NAVACTIVE(state, navActive) {
      state.navActive = navActive
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit, dispatch }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {
          const data = res.data
          const accessedRoutes = filterAsyncRouter(data)
          commit('SET_ROUTELIST', deepClone(accessedRoutes))
          accessedRoutes.push({ path: '*', redirect: '/error/404', hidden: true })
          resolve(accessedRoutes)
          const tempData = data.map(item => {
            item = {
              id: item.id,
              parentId: item.parentId,
              path: item.component || '',
              hidden: item.visible === '1',
              meta: {
                icon: item.icon,
                title: item.menuName
              },
              name: item.menuName,
              menuType: item.menuType
            }
            if (item.menuType === 'M') {
              item.alwaysShow = true
            }
            return item
          })
          const navMenu = arrayToTree(tempData)
          navMenu.forEach(item => {
            if (genRedirectInfo(item) !== null && genRedirectInfo(item) !== undefined) {
              item.redirect = `/${genRedirectInfo(item).path}`
              item.redirectId = genRedirectInfo(item).id
            }
          })
          commit('SET_ROUTES', navMenu)
          dispatch({
            type: 'genLeftList'
          })
        })
      })
    },
    // 生成左侧菜单
    genLeftList({ commit }, item) {
      if (item && item.children) {
        commit('SET_LEFTLIST', item.children)
      } else {
        commit('SET_LEFTLIST', [])
      }
    },
    // 更改当前激活的左侧菜单
    changeLeftActive({ commit }, leftActive) {
      Cookies.set('_sider_bar_active_', leftActive)
      commit('SET_LEFTACTIVE', leftActive)
    },
    // 更改当前菜单项
    changeNavActive({ commit, dispatch }, item) {
      Cookies.set('_nav_active_', item.id)
      commit('SET_NAVACTIVE', item.id)
      dispatch('genLeftList', item)
      if (item && item.meta) {
        Cookies.set('_no-name_', item.meta.title)
        Cookies.set('_no-id_', item.id)
      }
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  const router = []
  asyncRouterMap.forEach(route => {
    if (route.component && route.component.indexOf('?') === -1) { // 菜单不带参数
      route = {
        id: route.id,
        path: `/${route.component}`,
        component: Layout,
        children: [
          {
            path: `/${route.component}`,
            component: loadView(route.component),
            name: route.menuName,
            meta: {
              id: route.id,
              title: route.menuName
            }
          }
        ]
      }
      router.push(route)
    } else if (route.menuType === 'C' && route.component) { // 菜单带参数
      var spath = route.component.split('?')[0] // 路由
      var params = route.component.split('?')[1] // 参数
      var newstr = params.replace(/=/g, '":"')
      const objectKey = '{"' + newstr.replace(/&/g, '","') + '"}'
      const parameter = JSON.parse(objectKey)

      route = {
        id: route.id,
        path: `/${route.component}`,
        component: Layout,
        children: [
          {
            path: `/${spath}`,
            component: loadView(spath),
            name: route.menuName,
            query: parameter, // 参数
            meta: {
              id: route.id,
              title: route.menuName
            }
          }
        ]
      }
      router.push(route)
    }
  })
  return router
}

// 生成跳转信息
function genRedirectInfo(item) {
  if (item.menuType === 'C') {
    return item
  } else if (item.children && item.children[0]) {
    return genRedirectInfo(item.children[0])
  }
}

export const loadView = (view) => { // 路由懒加载
  return () => Promise.resolve(require(`@/views/${view}`).default)
}

export default permission
